<template xmlns="">
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <a-row class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden">
      <!-- 查询条件 -->
      <a-row v-if="showSearchRow" class="w-full">
        <a-form :model="searchForm" label-align="left" layout="inline" size="small">
          <a-form-item field="contractTemplateName" label="模板名称">
            <a-input
                v-model="searchForm.contractTemplateName"
                allow-clear
                placeholder="请输入模板名称"
            />
          </a-form-item>
          <a-form-item field="contractTemplateType" label="模板类型">
            <a-select
                v-model="searchForm.contractTemplateType"
                allow-clear
                placeholder="请选择模板类型"
            >
              <a-option v-for="(d, index) in dicts[proxy.DICT.contractTemplateType]" :key="index" :label="d.dictValue"
                        :value="d.dictKey"/>
            </a-select>
          </a-form-item>
        </a-form>
        <a-row class="w-full mt-2" justify="center">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon>
                <icon-search/>
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button @click="getPageList(true)">
              <template #icon>
                <icon-refresh/>
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2"/>

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-between">
        <a-space>
          <!-- 添加 -->
          <a-button
              size="small"
              type="primary"
              @click="handleAdd"
          >
            <template #icon>
              <icon-plus/>
            </template>
            <template #default>新增</template>
          </a-button>
        </a-space>
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon>
              <icon-refresh/>
            </template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button shape="circle" size="small" @click="showSearchRow = !showSearchRow">
            <template #icon>
              <icon-caret-up v-if="showSearchRow"/>
              <icon-caret-down v-else/>
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
            :columns="datatable.columns"
            :data="datatable.records"
            :loading="datatable.loading"
            :pagination="false"
            :row-key="'contractTemplateId'"
            :scroll="{ minWidth: 800, y: '100%' }"
            class="w-[100%]"
            table-layout-fixed
        >
          <!-- 模板名称列模板 -->
          <template #contractTemplateName="{ record }">
            <a-link icon @click="handleView(record)">{{ record.contractTemplateName }}</a-link>
          </template>
          <!-- 模板类型 -->
          <template #contractTemplateType="{ record }">
            <dict-convert
                :dict-data="dicts[proxy.DICT.lindiContractTemplateType]"
                :dict-key="record.contractTemplateType"
            />
          </template>
          <!-- 状态 -->
          <template #status="{ record }">
            <a-tag v-if="record.status === 1" color="green">启用</a-tag>
            <a-tag v-else color="red">禁用</a-tag>
          </template>
          <!-- 操作 -->
          <template #operation="{ record }">
            <a-button
                size="mini"
                type="text"
                @click="handleEdit(record)"
            >
              <template #icon>
                <icon-edit/>
              </template>
              <template #default>修改</template>
            </a-button>
            <a-popconfirm
                :content="`确定删除【${record.contractTemplateName}】吗?`"
                type="warning"
                @ok="onDeleteOK(record.contractTemplateId)"
            >
              <a-button
                  size="mini"
                  status="danger"
                  type="text"
              >
                <template #icon>
                  <icon-delete/>
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-row>

      <!-- 分页 -->
      <a-row class="w-full flex justify-end mt-2">
        <pagination
            v-if="datatable.total > 0"
            v-model:page-num="searchForm.pageNum"
            v-model:page-size="searchForm.pageSize"
            :total="datatable.total"
            @pagination="getPageList(false)"
        />
      </a-row>
    </a-row>

    <!-- 弹窗区域 -->
    <a-modal
        v-model:visible="modal.visible"
        :esc-to-close="false"
        :footer="false"
        :mask-closable="false"
        :width="1200"
        draggable
    >
      <template #title>{{ modal.title }}</template>
      <component
          :is="modal.component"
          v-if="modal.visible"
          :params="modal.params"
          @cancel="onCancel"
          @ok="onOk"
      />
    </a-modal>
  </a-card>
</template>

<script setup>
import {getCurrentInstance, reactive, ref} from "vue";
import ContractTemplateDetail from "~/pages/lindi/contractTemplate/ContractTemplateDetail.vue";
import ContractTemplateEdit from "~/pages/lindi/contractTemplate/ContractTemplateEdit.vue";
import {
  getPageContractTemplateListApi,
  deleteContractTemplateByContractTemplateIdApi
} from "~/api/lindi/contractTemplate";

// 全局实例
const {proxy} = getCurrentInstance();

// 加载字典
const dicts = proxy.LoadDicts([proxy.DICT.lindiContractTemplateType]);

// 是否展示搜索区域
const showSearchRow = ref(true);

// 搜索参数表单
const searchForm = reactive({
  // 模板名称
  contractTemplateName: null,
  // 模板类型
  contractTemplateType: null,
  // 页码
  pageNum: 1,
  // 条数
  pageSize: 10,
});

// 数据列表
const datatable = reactive({
  // 列配置
  columns: [
    {title: "模板名称", dataIndex: "contractTemplateName", slotName: "contractTemplateName", align: "center", width: 200},
    {title: "模板类型", dataIndex: "contractTemplateType", slotName: "contractTemplateType", align: "center", width: 120},
    {title: "状态", dataIndex: "status", slotName: "status", align: "center", width: 80},
    {title: "创建时间", dataIndex: "createTime", align: "center", width: 180},
    {title: "更新时间", dataIndex: "updateTime", align: "center", width: 180},
    {title: "操作", dataIndex: "operation", slotName: "operation", align: "center", width: 160, fixed: "right"},
  ],
  // 数据记录
  records: [],
  // 数据总数
  total: 0,
  // 加载状态
  loading: false,
});

// 弹窗
const modal = reactive({
  visible: false,
  title: "",
  component: null,
  params: {},
});



// 获取分页数据
const getPageList = (isReset) => {
  // 是否重置查询条件
  if (isReset) {
    searchForm.contractTemplateName = null;
    searchForm.contractTemplateType = null;
    searchForm.pageNum = 1;
  }

  datatable.loading = true;

  // 调用API获取数据
  getPageContractTemplateListApi(searchForm)
    .then(res => {
        datatable.records = res.records || [];
        datatable.total = res.total || 0;
    })
    .catch(error => {
      console.error('查询合同模板列表失败:', error);
      proxy.$message.error('查询失败，请稍后重试');
      datatable.records = [];
      datatable.total = 0;
    })
    .finally(() => {
      datatable.loading = false;
    });
};

// 新增
function handleAdd() {
  modal.visible = true;
  modal.title = "新增合同模板";
  modal.component = ContractTemplateEdit;
  modal.params = {};
}

// 查看
function handleView(record) {
  modal.visible = true;
  modal.title = "查看合同模板";
  modal.component = ContractTemplateDetail;
  modal.params = {
    contractTemplateId: record.contractTemplateId
  };
}

// 编辑
function handleEdit(record) {
  modal.visible = true;
  modal.title = "编辑合同模板";
  modal.component = ContractTemplateEdit;
  modal.params = {contractTemplateId: record.contractTemplateId};
}

// 单个删除确认
function onDeleteOK(contractTemplateId) {
  deleteContractTemplateByContractTemplateIdApi(contractTemplateId)
    .then(res => {
      if (res) {
        proxy.$message.success('删除成功');
        getPageList(false);
      } else {
        proxy.$message.error(res.message || '删除失败');
      }
    })
    .catch(error => {
      console.error('删除合同模板失败:', error);
      proxy.$message.error('删除失败，请稍后重试');
    });
}

// 取消
function onCancel() {
  modal.visible = false;
}

// 确定
function onOk() {
  modal.visible = false;
  getPageList(false);
}

// 初始加载数据
getPageList(true);
</script>